window.onload = function() {
    clickGotoTop();
    ifLoged();
    loadArticle(1);
    window.addEventListener('scroll', _.throttle(lazyLoad(), 100));
    window.addEventListener('scroll', _.throttle(checkImg, 100));
}

function lazyLoad() {
    if (pageIndex === undefined) {
        var pageIndex = 2;
    }
    // var timestamp = (new Date()).valueOf();
    // console.log(loading.getBoundingClientRect().top);
    // console.log(loading.offsetHeight);
    // console.log(document.documentElement.clientHeight);
    // console.log("------------------------------------");
    return function() {
        var loading = document.getElementById("loading");
        if (loading.getBoundingClientRect().top + loading.offsetHeight < document.documentElement.clientHeight) {
            // var timestampnow = (new Date()).valueOf();
            // console.log(timestamp);
            // console.log(timestampnow);
            // if (timestampnow - timestamp <= 1000 && timestampnow - timestamp > 100) {}
            loadArticle(pageIndex++);
            // 当正在加载图标出现在视窗中时，请求下一页文章列表。
        }
    }
}

function checkImg() {
    var imgs = document.getElementsByClassName("cover");
    for (var index = 0; index < imgs.length; index++) {
        var imageHeight = imgs[index].offsetTop;
        if (imageHeight < document.documentElement.clientHeight + document.documentElement.scrollTop) {
            preload_images(imgs[index]);
            // imgs[index].classList.remove("cover");
            imgs[index].className = imgs[index].className.replace('cover', '');
        }
    }
};

function preload_images(img) {
    var temp_img = new Image();
    //预加载图片
    // temp_img.src = url_file + img.dataset.src;
    temp_img.src = img.dataset.src;
    // temp_img.src = "images/1.jpg";
    //图片加载成功后，替换临时图片
    temp_img.onload = function() {
            // img.src = url_file + img.dataset.src;
            img.src = "image/2.jpg";
        }
        //加载失败
    temp_img.onerror = function() {
        img.src = "image/loadfail.jpg";
    }
}

function loadArticle(pageIndex) {
    // 请求文章列表接口。
    //
    var data = {
            "code": "SUCCESS",
            "data": {
                "articles": [{
                    "_id": "5a17f9cd396c3149ac92aea5",
                    "title": "我和你一样，写不好文章",
                    "cover": "cover/8c46e80190317dd979bb530db2059e85",
                    "abstract": "生活不只有现在的苟且，还有将来的。 2017年11月24日 星期五 有风 文|南有南风 -1- 最开始我以为阅读量高是好文章，于是我想着写爆文。多一个阅读，我就开心一点，...",
                    "create_time": 1511507522000,
                    "author": {
                        "_id": "5a17f9c9396c3149ac92ae6d",
                        "name": "南有南风",
                        "gender": "man",
                        "constellations": "射手座",
                        "avatar": "avatar/622545f85c56524fa31b93d60e990133",
                        "city": ["台湾 金门县"]
                    },
                    "look_sum": 790,
                    "praise_sum": 95
                }, {
                    "_id": "5a17f9d2396c3149ac92aef9",
                    "title": "我羞于启齿了20年后，才知道从小应该了解“性”",
                    "cover": "cover/8ff10545e35b595e9fdfa6c592805e33",
                    "abstract": "今天是《嘉年华》上映的日子，被称为中国版的“熔炉”，比起中文名字，我更喜欢这部电影的英文名字“Angles wear white”，一部直面国人内心愤恨与恐惧的片子。而最近，...",
                    "create_time": 1511506587000,
                    "author": {
                        "_id": "5a17f9c9396c3149ac92ae7a",
                        "name": "婧妹坨",
                        "gender": "woman",
                        "constellations": "水瓶座",
                        "avatar": "avatar/b768e6ec1f4051d1565820133886040b",
                        "city": ["台湾 金门县"]
                    },
                    "look_sum": 297,
                    "praise_sum": 23
                }, {
                    "_id": "5a17f9da396c3149ac92af77",
                    "title": "你用过真实的iPhone手机吗？",
                    "cover": "cover/e0077a4f297109726d575e644db66b51",
                    "abstract": "我一直有个习惯，出去逛街的时候每次经过苹果的零售店都要进去看看，尽管我绝大多数的时候都不买，或许就是因为喜欢店里的那种氛围吧。 1 在苹果店里的时候我经常能碰见很多拿着iPh...",
                    "create_time": 1511505342000,
                    "author": {
                        "_id": "5a17f9c9396c3149ac92ae97",
                        "name": "马虎眼",
                        "gender": "man",
                        "constellations": "双子座",
                        "avatar": "avatar/f0ad5739411a61265ebdfc84de037365",
                        "city": ["江西省 吉安市"]
                    },
                    "look_sum": 354,
                    "praise_sum": 4
                }, {
                    "_id": "5a17f9d0396c3149ac92aedd",
                    "title": "后半生，只爱一个人",
                    "cover": "cover/fd0d20ffdb254a9f22f1e617fba36283",
                    "abstract": "我不知道爱不爱你父亲，我只知道，看到或是想到他一个人孤零零的，我的心会疼…… 01. 刘梅香到老胡家当保姆时48岁。当时老胡的妻子马丽住院，已经昏迷了半个多月。老胡在医院陪护...",
                    "create_time": 1511504452000,
                    "author": {
                        "_id": "5a17f9c9396c3149ac92ae72",
                        "name": "井底女蛙",
                        "gender": "man",
                        "constellations": "天蝎座",
                        "avatar": "avatar/ce0bddb1d08902ab96a3c4ec8a0c5ae2",
                        "city": ["江苏省 南通市"]
                    },
                    "look_sum": 1037,
                    "praise_sum": 95
                }]
            },
            "count": 235
        } // ajaxXHR('GET', url + "posts/list?page=" + pageIndex + "&limit=4", function(data) {
    var essayData = data.data.articles;
    var essay = "";
    for (let i = 0; i < essayData.length; i++) {
        const e = essayData[i];
        essay += '<div class="essayList-item">';
        essay += '<a class="openArticle" href="articleDetail.html?id=' + e._id + '">';
        // preloadImages
        loadpath = "image/loading.gif";
        realpath = "image/success.jpg";
        // realpath = url_file + e.cover;
        essay += '<img class="essay-pic cover" data-src="' + realpath + '" src="' + loadpath + '">';
        essay += '</a><div class = "essaySummary"><div class="title"><a class="openArticle" href="articleDetail.html?id=' + e._id + '" ><p class="font18">';
        essay += e.title + '</p></a></div>';
        essay += '<p class="abstract">' + e.abstract + '</p><div class ="meta">';
        //使用本地图片以节约资源
        preavatar = "image/3.jpg";
        avatarpath = url_file + e.author.avatar;
        essay += '<a class ="author" href="homepage.html?id=' + e.author._id + '&constellations=' + e.author.constellations + '&avatar=' + e.author.avatar + '&gender=' + e.author.gender + '&city=' + e.author.city + '&name=' + e.author.name + '">';
        essay += '<img class = "author-icon" src ="' + preavatar + '"><p class="authorName">' + e.author.name + '</p>';
        // moment.js 格式化时间戳
        essay += '<p class="publishTime">' + moment(e.create_time).format('YYYY-MM-DD HH:mm:ss') + '</p>'
        essay += '</a> <span class = "praiseCount" > <i> </i>' + e.praise_sum + '</span>';
        essay += '<span class="visitCount"><i> </i>' + e.look_sum + '</span></div></div></div>';
    }
    document.getElementById("loading").insertAdjacentHTML('beforebegin', essay);
    //     if (data.code != "SUCCESS" || data.data.articles.length == 0) {
    //         document.getElementById("loading").innerHTML = "<strong>没有更多文章！</strong>"
    //         return false;
    //     }
    //     var essayData = data.data.articles;
    //     var essay = "";
    //     for (let i = 0; i < essayData.length; i++) {
    //         essay += '<div class="essayList-item">';
    //         essay += '<a class="openArticle"  href="articleDetail.html?_id=' + e._id + '">';
    //         // preloadImages
    //         loadpath = "image/icon-loading.gif";
    //         realpath = url_file + e.cover;
    //         essay += '<img class="essay-pic cover" data-src="' + realpath + '" src="' + loadpath + '">';
    //         essay += '</a><div class = "essaySummary"><div class="title"><a class="openArticle"  href="articleDetail.html?data-id=' + e._id + '" >'
    //         essay += e.title + '</a></div>'
    //         essay += '<p class="abstract">' + e.abstract + '</p>'
    //         preavatar = "image/3.jpg";
    //         avatarpath = url_file + e.author.avatar;
    //         essay += '<div class ="meta"><div class ="author">' + '<img class = "author-icon" src ="' + preavatar + '">'
    //         essay += '<p class="authorName">' + e.author.name + '</p>'
    //             // moment.js 格式化时间戳
    //         essay += '<p class="publishTime">' + moment(e.create_time).format('YYYY-MM-DD HH:mm:ss') + '</p>'
    //         essay += '</div> <span class = "praiseCount" > <i> </i>' + e.praise_sum + '</span>';
    //         essay += '<span class="visitCount"><i> </i>' + e.look_sum + '</span></div></div></div>';
    //     }
    //     document.getElementById("loading").insertAdjacentHTML('beforebegin', essay);
    // })
    checkImg();
    // })
}

function clickGotoTop() {
    /**
     * 自动跳转至页首
     */
    var clickToTop = document.getElementsByClassName("clickgoTop")[0];
    var clientHeight = document.documentElement.clientHeight;
    var timer = null;
    var isTop = true;
    //根据高度判断是否隐藏按钮
    window.onscroll = function() {
        /**
         * //获取页面卷起高度
         */
        var overtop = document.documentElement.scrollTop || document.body.scrollTop;
        if (overtop >= clientHeight) {
            clickToTop.style.visibility = "visible";
        } else {
            clickToTop.style.visibility = "hidden";
        };
        if (!isTop) {
            clearInterval(timer);
        }
        isTop = false;
    }
    clickToTop.onclick = function() {
        timer = setInterval(function() {
            var overtop = document.documentElement.scrollTop || document.body.scrollTop;
            var speed = Math.floor(-overtop / 7);
            document.documentElement.scrollTop = document.body.scrollTop = overtop + speed;
            if (overtop == 0) {
                clearInterval(timer);
            }
            isTop = true;
        }, 30)
    }

}